/*============================================================================
  File:    Service1.cs

  Summary: Contains class implementiong ASTrace service

           Part of ASTrace 

  Date:    January 2007
------------------------------------------------------------------------------
  This file is part of the Microsoft SQL Server Code Samples.

  Copyright (C) Microsoft Corporation.  All rights reserved.

  This source code is intended only as a supplement to Microsoft
  Development Tools and/or on-line documentation.  See these other
  materials for detailed information regarding Microsoft code samples.

  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;

namespace ASTrace
{
    public partial class Trace : ServiceBase
    {
        Thread worker;
        TraceTable tableWriter;
        string localPath;

        public Trace()
        {
            InitializeComponent();

            // Read registry to find out where the service executable is installed 
            Microsoft.Win32.RegistryKey software, microsoft, astrace;
            software = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE");
            microsoft = software.OpenSubKey("Microsoft");
            astrace = microsoft.OpenSubKey("ASTrace");
            localPath = (string) astrace.GetValue("path"); 

            TextWriter writer = new StreamWriter( localPath + "\\ASTraceService.log", true);

            writer.WriteLine(DateTime.Now.ToString() + ":  Service Started in '" + localPath + "'");
            writer.Close();
            writer.Dispose();
        }

        protected override void OnStart(string[] args)
        {

            TextWriter writer = new StreamWriter(localPath + "\\ASTraceService.log", true);

            OlapConnectionInfo ci = new OlapConnectionInfo();
            TraceServer traceServer = new TraceServer();
            try
            {
                ci.UseIntegratedSecurity = true;
                ci.ServerName = Properties.Settings.Default.AnalysisServerName;
                string tracetemplate = localPath + "\\" + Properties.Settings.Default.TraceDefinition;
                traceServer.InitializeAsReader(ci, tracetemplate);
                writer.WriteLine(DateTime.Now.ToString() + ":  Created trace for Analysis Server : '" + 
                    Properties.Settings.Default.AnalysisServerName + "'");
            }
            catch (Exception e)
            {
                writer.WriteLine(DateTime.Now.ToString() + ":  Cannot start Analysis Server trace: ");
                writer.WriteLine(DateTime.Now.ToString() + ":  Analysis Server name: '" + 
                    Properties.Settings.Default.AnalysisServerName + "'");
                writer.WriteLine(DateTime.Now.ToString() + ":  Trace defintion : '" + localPath + "\\" + Properties.Settings.Default.TraceDefinition + "'");
                writer.WriteLine(DateTime.Now.ToString() + ":  Error: " + e.ToString());
                writer.Close();
                Stop();
            }

            SqlConnectionInfo connInfo = new SqlConnectionInfo(Properties.Settings.Default.SQLServer);
            tableWriter = new TraceTable();
            try
            {
                connInfo.DatabaseName = Properties.Settings.Default.SQLServerDatabase;
                tableWriter.InitializeAsWriter(traceServer, connInfo, Properties.Settings.Default.TraceTableName);
                writer.WriteLine(DateTime.Now.ToString() + ":  Created Analysis Server trace table: '" 
                    + Properties.Settings.Default.TraceTableName 
                    + "' on SQL Server: '" + Properties.Settings.Default.SQLServer 
                    + "' in database: " + Properties.Settings.Default.SQLServerDatabase + "'");
            }
            catch (Exception e)
            {
                writer.WriteLine(DateTime.Now.ToString() + ":  Cannot create Analysis Server trace table: '" + Properties.Settings.Default.AnalysisServerName + "'");
                writer.WriteLine(DateTime.Now.ToString() + ":  SQL Server name: '" + Properties.Settings.Default.SQLServer + "'");
                writer.WriteLine(DateTime.Now.ToString() + ":  SQL Server table : '" + Properties.Settings.Default.SQLServerDatabase + "'");
                writer.WriteLine(DateTime.Now.ToString() + ":  Error: " + e.ToString());
                writer.Close();
                Stop();
            }

            writer.Close();

            worker = new Thread(DoWork);
            worker.Start();

        }

        void DoWork()
        {

            try
            {
                while (tableWriter.Write()) { };
            }
            catch {
                Stop();
            }
        }

        protected override void OnStop()
        {
        }

    }
}
